package com.nageoffer.shortlink.project.service.Impl;

import com.nageoffer.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;


@Service
public class UrlTitleServiceImpl implements UrlTitleService {

    @Override
    @SneakyThrows
    public String getTitleByUrl(String url) {
        URL targetUrl = new URL(url); // 将字符串 URL 转换为 URL 对象
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection(); // 打开与该 URL 的连接
        connection.setRequestMethod("GET"); // 设置请求方式为 GET
        connection.connect(); // 建立实际连接

        int responseCode = connection.getResponseCode(); // 获取 HTTP 响应状态码
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 判断应状态码为 200（表示请求成功）
            Document document = Jsoup.connect(url).get(); // 用 Jsoup 连接 URL 并获取网页文档
            return document.title();
        }
        return "Error while fetching title";


    }
}

